﻿using System;
using System.Windows.Forms;
using WorkLogger.Client.Controls;
using WorkLogger.Client.DataAccess.Model;
using WorkLogger.Client.Forms;

namespace WorkLogger.Client.Presenters {
	public class LunchTimePresenter {
		private readonly ILunchTimeView lunchTimeView;
		private readonly IWorkDayManager workDayManager;

		public event EventHandler LunchChanged;

		public LunchTimePresenter(ILunchTimeView lunchTimeView, IWorkDayManager workDayManager) {
			this.lunchTimeView = lunchTimeView;
			this.workDayManager = workDayManager;
			lunchTimeView.AddLunch += LunchTimeViewAddLunch;
			lunchTimeView.EditLunch += LunchTimeViewEditLunch;
			lunchTimeView.RemoveLunch += LunchTimeViewRemoveLunch;
		}

		private void LunchTimeViewRemoveLunch(object sender, EventArgs e) {
			LunchTime selectedLunch = lunchTimeView.SelectedLunch;
			if (selectedLunch == null)
				return;

			if (MessageBox.Show("Вы действительно хотите удалить перерыв на обед?", "Удаление перерыва на обед",
			                    MessageBoxButtons.YesNo) == DialogResult.Yes) {
				workDayManager.GetCurrentWorkDay().LunchTimes.Remove(selectedLunch);
				UpdateWorkDay();
			}
		}

		private void LunchTimeViewEditLunch(object sender, EventArgs e) {
			LunchTime selectedLunch = lunchTimeView.SelectedLunch;
			if (selectedLunch == null)
				return;

			using (var form = new EditLunchTimeForm()) {
				form.ActionName = "Сохранить";
				form.StartLunch = selectedLunch.StartLunch;
				form.EndLunch = selectedLunch.EndLunch;

				if (form.ShowDialog() == DialogResult.OK) {
					selectedLunch.StartLunch = TruncateSeconds(form.StartLunch);
					selectedLunch.EndLunch = TruncateSeconds(form.EndLunch);

					UpdateWorkDay();
				}
			}
		}

		private static DateTime TruncateSeconds(DateTime dateTime) {
			return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, 0);
		}

		private void UpdateWorkDay() {
			workDayManager.Update();
			if (LunchChanged != null) {
				LunchChanged(this, EventArgs.Empty);
			}
		}

		private void LunchTimeViewAddLunch(object sender, EventArgs e) {
			using (var form = new EditLunchTimeForm()) {
				form.ActionName = "Добавить";
				if (form.ShowDialog() == DialogResult.OK) {
					WorkDay currentWorkDay = workDayManager.GetCurrentWorkDay();
					currentWorkDay.LunchTimes.Add(new LunchTime {
					                                            	WorkDay = currentWorkDay,
					                                            	StartLunch = TruncateSeconds(form.StartLunch),
					                                            	EndLunch = TruncateSeconds(form.EndLunch)
					                                            });

					UpdateWorkDay();
				}
			}
		}

		public void Update() {
			lunchTimeView.SetLunches(workDayManager.GetCurrentWorkDay().LunchTimes);
		}
	}
}